package com.learn.xueer.data.repository.request

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import com.learn.xueer.app.network.apiService
import com.learn.xueer.app.network.apiServiceOrg
import com.learn.xueer.app.util.CacheUtil
import com.learn.xueer.data.model.bean.ApiResponse
import me.hgj.jetpackmvvm.network.AppException
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.awaitResponse

/**
 * 作者　: hegaojian
 * 时间　: 2020/5/4
 * 描述　: 处理协程的请求类
 */

val HttpRequestCoroutine: HttpRequestManger by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
    HttpRequestManger()
}

class HttpRequestManger {
    suspend fun captcha(id: String): ByteArray? {
        val registerData = apiServiceOrg.captcha(id)
        var awaitResponse = registerData.awaitResponse()
        if (awaitResponse.isSuccessful) {
            val body: ResponseBody? = awaitResponse.body()
            if (body != null) {
                return body.bytes()
            }
            return null
        } else {
            //抛出错误异常
            throw AppException(awaitResponse.code(), awaitResponse.message())
        }
    }
}